<template>
  <a-drawer
      v-model:open="isShow"
      class="custom-class"
      title="新增"
      size="large"
      placement="right"
      @close="close"
  >
    <a-card>
      <a-form
          ref="form"
          :model="formState"
          autocomplete="off"
          :rules="rules"
          style="padding: 25px"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 14 }"
      >
        <a-form-item label="用户账户" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>
        <a-form-item  label="登录密码" name="password">
          <a-input v-model:value="formState.password" type="password" autocomplete="off" />
        </a-form-item>
        <a-form-item  label="确认密码" name="confirmpassword">
          <a-input v-model:value="formState.confirmpassword" type="password" autocomplete="off" />
        </a-form-item>
        <a-form-item label="用户姓名" name="realname">
          <a-input v-model:value="formState.realname" />
        </a-form-item>
        <a-form-item label="手机号码" name="phone">
          <a-input v-model:value="formState.phone" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>
<!--        <a-form-item label="职务">-->
<!--          <a-select-->
<!--              v-model:value="formState.post"-->
<!--              mode="tags"-->
<!--              style="width: 100%"-->
<!--              placeholder="请选择职务"-->
<!--              :options="postOptions"-->
<!--          ></a-select>-->
<!--        </a-form-item>-->
        <a-form-item label="角色分配">
          <a-select
              v-model:value="formState.selectedroles"
              mode="tags"
              style="width: 100%"
              placeholder="请选择角色"
              :options="rolesOptions"
          ></a-select>
        </a-form-item>

        <!--部门分配-->
<!--        <a-form-item label="部门分配">-->
<!--          <j-select-depart v-model="formState.selecteddeparts" :multi="true" @back="backDepartInfo" :backDepart="true" :treeOpera="true">></j-select-depart>-->
<!--        </a-form-item>-->

        <!--租户分配-->
<!--        <a-form-item label="租户分配">-->
<!--          <a-select-->
<!--              v-model:value="formState.relTenantIds"-->
<!--              mode="tags"-->
<!--              style="width: 100%"-->
<!--              placeholder="请选择租户"-->
<!--              :options="tenantsOptions"-->
<!--          ></a-select>-->
<!--        </a-form-item>-->
        <a-form-item label="身份" name="userIdentity">
          <a-radio-group  v-model:value="formState.userIdentity"  @change="identityChange">
            <a-radio value="1">普通用户</a-radio>
            <a-radio value="2">上级</a-radio>
          </a-radio-group>
        </a-form-item>
<!--        <a-form-item label="负责部门" v-if="formState.userIdentity==='2'">-->
<!--          <a-select-->
<!--              v-model:value="formState.departIds"-->
<!--              mode="tags"-->
<!--              style="width: 100%"-->
<!--              placeholder="负责部门"-->
<!--              :options="nextDepartOptions"-->
<!--          ></a-select>-->
<!--        </a-form-item>-->
        <a-form-item label="头像">
          <a-upload
              name="file"
              listType="picture-card"
              :multiple="false"
              :action="uploadAction"
              :headers="headers"
              :beforeUpload="beforeUpload"
              @preview="handlePreview"
          >
            <img v-if="previewImage" :src="previewImage" alt="avatar" />
            <div v-else>
              <PlusOutlined />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="生日">
          <a-date-picker
              style="width: 100%"
              placeholder="请选择生日"
              v-model:value="formState.birthday"
              format="YYYY-MM-DD"
              :getPopupContainer="(node) => node.parentNode"/>
        </a-form-item>
        <a-form-item label="性别">
          <a-select  v-model="formState.sex"  placeholder="请选择性别" :getPopupContainer= "(target) => target.parentNode">
            <a-select-option value="1">男</a-select-option>
            <a-select-option value="2">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="座机" name="telephone">
          <a-input  v-model:value="formState.telephone" />
        </a-form-item>
        <a-form-item label="工作流引擎">
          <a-radio-group  v-model:value="formState.activitiSync">
            <a-radio value="1">同步</a-radio>
            <a-radio value="0">不同步</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <div style="display: flex; justify-content: end">
        <a-button style="margin-right: 5px" @click="close">关闭</a-button>
        <a-button type="primary" @click="submit" :loading="loading">确定</a-button>
      </div>
    </a-card>
  </a-drawer>
</template>
<script setup>
import {computed, onMounted, ref} from "vue";
import {useValidateUser} from "@/views/system/validateUser/index.js";
import {addUser, getRoleList} from "@/api/system/user.js";
import {message} from "ant-design-vue";
import {apiBaseUrl} from "@utils/service/index.js";
import {getToken} from "@utils/storage.js";
const emit = defineEmits(['handleClose'])
const userId = ref('1')
const form = ref()
const uploadAction = ref(apiBaseUrl + '/sys/common/upload')
const previewImage = ref('')
const headers = ref({
  "X-Access-Token":getToken()
})
const loading = ref(false)
const isShow = computed(() => props.openA)

const {validateUsername,compareToFirstPassword,formState,validateEmail,reset} = useValidateUser({
  userId:userId.value,
})

const postOptions = ref([
  {
    value: '总经理'
  }
])
const rolesOptions = ref([])
const tenantsOptions = ref([])
const nextDepartOptions = ref([])
/**
 * 上传图片之前的校验
 * @param file {File} 文件对象
 * @returns {boolean}
 */
const beforeUpload = (file) => {
  let fileType = file.type;
  if(fileType.indexOf('image')<0){
    message.warning('请上传图片');
    return false;
  }
}
/**
 * 上传图片预览
 * @param file {File} 文件对象
 */
const handlePreview = (file) => {
  previewImage.value = file.url || file.thumbUrl
}
const rules = {
    username:[
        {required: true, message: '请输入用户账号!'},
        {validator: validateUsername, trigger: 'change'}
    ],
    // password: [
    //     {required: true,trigger: 'change',
    //       pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
    //       message: '密码由8位数字、大小写字母和特殊符号组成!'},
    // ],
    // confirmpassword: [
    //     {required: true, message: '请重新输入登录密码!',},
    //     { validator: compareToFirstPassword, trigger: 'change'}
    // ],
    // realname:[{ required: true, message: '请输入用户名称!' }],
    // email: [{validator: validateEmail}],
    // roles:[{}],
    // telephone: [{ pattern: /^0\d{2,3}-[1-9]\d{6,7}$/, message: '请输入正确的座机号码' },]
}
const props = defineProps({
  openA:{
    type: Boolean,
    default: false
  }
})
/**
 * 提交表单
 */
const submit = () => {
  form.value.validate()
      .then(async () => {
          try{
            loading.value = true
            const res = await addUser(formState)
            message.success('新增用户成功')
            close()
            loading.value = false
            form.value.resetFields()
          }catch(e){
            console.log(e);
            message.error(e)
          }
      })
      .catch(err => {
        loading.value = false
      });
}
/**
 * 初始化角色列表
 * @returns {Promise<void>}
 */
const initRoleList = async () =>{
    try {
      const res = await getRoleList()
      rolesOptions.value = res.result.map((item,index,arr)=>{
        return {label:item.roleName, value:item.id}
      })
      console.log(rolesOptions.value)
    }catch(e){
      message.error(e)
    }
}
/**
 * 获取用户部门信息
 * @param userid
 * @returns {Promise<void>}
 */
const getUserDeparts = async (userid) => {
  let that = this;
  const res = await getAction(that.url.userWithDepart,{userId:userid})
    if(res.success){
      let departOptions = [];
      let selectDepartKeys = []
      for (let i = 0; i < res.result.length; i++) {
        selectDepartKeys.push(res.result[i].key);
        //新增负责部门选择下拉框
        departOptions.push({
          value: res.result[i].key,
          label: res.result[i].title
        })
      }
      formState.selecteddeparts = selectDepartKeys.join(",")
      nextDepartOptions.value = departOptions;
      console.log('that.nextDepartOptions=',nextDepartOptions.value)
    }
}
const close = () => {
  emit('handleClose')
  reset()
}
onMounted(() => {
  initRoleList()
  // getUserDeparts(userId.value)
})
</script>
<style scoped>

</style>
